package online.heycm.codegenerator.service;

import online.heycm.codegenerator.common.error.CodeMsg;
import online.heycm.codegenerator.common.session.Session;
import online.heycm.platform.common.entity.result.Result;
import online.heycm.platform.common.tools.file.FileUtil;
import online.heycm.platform.web.common.sse.SseServer;
import online.heycm.platform.web.common.sse.SseSession;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.List;

/**
 * SSE 服务
 *
 * @author heycm
 * @since 2023/12/21 21:25
 */
@RestController
@RequestMapping("/sse")
public class SseService {

    @GetMapping(value = "/connect/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(@PathVariable String id) {
        return SseServer.connect(id).getSseEmitter();
    }

    @PostMapping("/close")
    public Result close(Session session) {
        SseServer.close(session.getToken());
        return Result.success();
    }

    @GetMapping("/preview")
    public Result preview(Integer fileIndex, Session session) throws IOException {
        // 索引找到文件
        if (fileIndex == null || fileIndex < 0) {
            return Result.error(CodeMsg.INVALID_FILE);
        }
        List<File> files = FileUtil.traverseDirectory(session.getOutput());
        if (CollectionUtils.isEmpty(files) || fileIndex >= files.size()) {
            return Result.error(CodeMsg.INVALID_FILE);
        }
        File file = files.get(fileIndex);
        if (!file.exists() || !file.isFile()) {
            return Result.error(CodeMsg.INVALID_FILE);
        }
        // 取SSE
        SseSession sseSession = SseServer.getSession(session.getToken());
        if (sseSession == null || !sseSession.isAlive()) {
            return Result.error(CodeMsg.INVALID_SSE);
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath())))) {
            String line;
            while ((line = reader.readLine()) != null) {
                final boolean send = sseSession.send(line);
                if (!send) {
                    return Result.error(CodeMsg.INVALID_SSE);
                }
            }
        }
        sseSession.close();
        return Result.success();
    }

}
